<template>
  <div>
    <div>
      <el-input style="width: 200px" placeholder="查询监控" v-model="cameraId"></el-input>
<!--      <el-input style="width: 200px; margin: 0 5px" placeholder="查询时间段"  v-model="date"></el-input>-->
      <el-button type="primary" @click="load(1)">查询</el-button>
      <el-button type="info" @click="reset">重置</el-button>
    </div>
    <div style="margin: 10px 0">
      <el-button type="primary" plain @click="handleAdd">新增</el-button>
      <el-button type="danger" plain @click="delBatch">批量删除</el-button>
      <el-button type="info" plain @click="exportData">批量导出</el-button>
      <el-upload :action="$baseUrl + '/user/import'" :headers="{token: user.token}" :on-success="handleImport" style="display: inline-block; margin-left: 10px" :show-file-list="false">
        <el-button type="primary" plain>批量导入</el-button>
      </el-upload>
    </div>
    <el-table :data="tableData" stripe :header-cell-style="{ backgroundColor: 'aliceblue', color: '#666' }" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="id" label="序号" width="70" align="center"></el-table-column>
      <el-table-column prop="name" label="视频名"></el-table-column>
      <el-table-column prop="date" label="记录日期"></el-table-column>
      <el-table-column label="操作" align="center" width="180">
        <template v-slot="scope">
          <el-button size="mini" type="success" plain @click="start(scope.row)">播放</el-button>
          <el-button size="mini" type="danger" plain @click="handleEdit(scope.row)">下载</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 播放视频弹窗 -->
    <el-dialog title="视频播放" :visible.sync="videoVisible" width="60%">
      <video
          v-if="videoUrl"
          :src="videoUrl"
          controls
          autoplay
          style="width: 100%; height: auto;"
      ></video>
    </el-dialog>

    <div style="margin: 10px 0">
      <el-pagination
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-size="pageSize"
          layout="total, prev, pager, next"
          :total="total">
      </el-pagination>
    </div>


  </div>
</template>

<script>
export default {
  name: "Map",
  data() {
    return {
      tableData: [],  // 所有的数据
      pageNum: 1,   // 当前的页码
      pageSize: 5,  // 每页显示的个数
      cameraId : '2',
      videoVisible: false,
      videoUrl: "",
      date: '',
      total: 0,
      fromVisible: false,
      form: {},
      user: JSON.parse(localStorage.getItem('honey-user') || '{}'),
      ids: []
    }
  },
  created() {
    this.load()
  },
  methods: {
    delBatch() {
      if (!this.ids.length) {
        this.$message.warning('请选择数据')
        return
      }
      this.$confirm('您确认批量删除这些数据吗？', '确认删除', {type: "warning"}).then(response => {
        this.$request.delete('/user/delete/batch', { data: this.ids }).then(res => {
          if (res.code === '200') {   // 表示操作成功
            this.$message.success('操作成功')
            this.load(1)
          } else {
            this.$message.error(res.msg)  // 弹出错误的信息
          }
        })
      }).catch(() => {})
    },
    handleSelectionChange(rows) {   // 当前选中的所有的行数据
      this.ids = rows.map(v => v.id)
    },

    // 待写
    start(row) {
      if (!row || !row.name) {
        this.$message.warning('无效的视频项');
        return;
      }

      // 调用后端接口检查文件是否存在（可选）
      this.$request.get(`/Video/stream/${this.cameraId}/${encodeURIComponent(row.name)}`, { responseType: 'blob' })
          .then(res => {
            // 如果返回 blob，说明文件存在，可以播放
            const blobUrl = URL.createObjectURL(res);
            this.videoUrl = blobUrl;
            this.videoVisible = true;

            this.$nextTick(() => {
              const v = this.$refs.videoPlayer;
              if (v && v.play) {
                v.play().catch(() => {}); // 避免浏览器阻止自动播放报错
              }
            });
          })
          .catch(err => {
            console.error('视频播放失败', err);
            this.$message.error('视频播放失败，文件可能不存在');
          });
    },
    reset() {
      this.name = ''
      this.username = ''
      this.load()
    },
    load(pageNum) {  // 分页查询
      if (pageNum) this.pageNum = pageNum
      this.$request.get(`/Video/list/${this.cameraId}`)
          .then(res => {
            console.log(res)
            this.tableData = res.data
            this.total = res.data.total   // 后端没返回 total，就用数组长度
          })
    },
    handleCurrentChange(pageNum) {
      this.load(pageNum)
    },
    handleAvatarSuccess(response, file, fileList) {
      // 把user的头像属性换成上传的图片的链接
      this.form.avatar = response.data
    },
  }
}
</script>

<style scoped>

</style>
